<!--设置角色权限
 -->
<template>
  <div class="app-container paddingT50">
    <div class="paddingLR20 clearfix">
      <el-card shadow="never" class="oper-btn-card">
        <div class="clearfix">
          <div class="fl">
            <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSaveData">保存</el-button>
            <el-button type="default" size="medium" @click="btnCancle">取消</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-card shadow="never" class="border-radius-none margin-t2">
      <!-- dataObj: {{ dataObj }} -->
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width="100px"
        size="mini"
      >
        <h3>基础信息</h3>
        <el-divider />
        <div class="paddingTb20 w600">
          <el-form-item :label="`角色名称:`" prop="realName">
            <el-input v-model="formData.name" readonly />
          </el-form-item>
          <el-form-item :label="`备注:`" prop="remark">
            <el-input v-model="formData.remark" readonly />
          </el-form-item>
          <el-form-item label="所属应用:" prop="relAppName">
            <el-input v-model="formData.relAppName" readonly />
          </el-form-item>
          <h3>设置菜单按钮资源</h3>
          <el-divider />
          <el-form-item label="">
            <el-tree
              ref="menuTree"
              :data="treeMenuData"
              :props="props"
              :node-key="treeNodeKey"
              :load="loadMenuNode"
              :default-checked-keys="defaultCheckedKeys"
              default-expand-all
              show-checkbox
              @check="checkNode"
            />
          </el-form-item>
          <h3>设置api资源</h3>
          <el-divider />
          <el-form-item label="">
            <el-tree
              ref="apiTree"
              :data="treeApiData"
              :props="props"
              :node-key="treeNodeKey"
              :load="loadApiNode"
              :default-checked-keys="defaultCheckedKeys"
              default-expand-all
              show-checkbox
              @check="checkNode"
            />
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { findById } from '@/api/role/role.js'
import { findAppByEnableStatus } from '../../../api/application/application'
import { findByRoleId, getApiTree, getTree } from '../../../api/resource/resource'
import { bindResource } from '../../../api/role/role'

export default {
  label: 'SysRoleAdd',
  mixins: [oftenuse],
  props: {
    operation: {
      type: String,
      default: null,
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1
      }
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      props: {
        id: 'id',
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      treeMenuData: [],
      defaultCheckedKeys: [],
      treeApiData: [],
      treeNodeKey: 'id',
      imageUrl: '',
      appOptions: [],
      appLoading: false,
      appLoad: false,
      resources: [],
      bindResources: [],
      unBindResources: [],
      formData: {
        name: null,
        code: null,
        remark: null,
        relAppName: null
      },
      originDataObj: {}, // 编辑状态初始值，用于对比是否修改
      optionsData: {},
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: false, message: '请输入角色编码', trigger: 'blur' }
        ],
        remark: [
          { required: false, message: '请输入备注', trigger: 'blur' }
        ],
        relAppId: [
          { required: true, message: '请选择所属应用', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 页面初始化数据写在这里
    this.initData()
    this.findAppByEnableStatus()
  },
  methods: {
    btnSaveData() {
      this.valiData().then(_ => {
        const params = this.formData
        this.setBtnLoading('save', true)
        this.saveData(params).then(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.appLoading = true
        setTimeout(() => {
          this.appLoading = false
          this.appOptions = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.appOptions = []
      }
    },
    findAppByEnableStatus() {
      findAppByEnableStatus({ enableStatus: 'NORMAL' }).then(res => {
        this.appLoad = true
        if (res.data.flag) {
          this.appOptions = res.data.result.map(item => {
            return { value: item.id, label: item.name }
          })
        }
      })
    },
    jump2list() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'sysRoleList',
        params: { refresh: true }
      })
    },
    btnCancle() {
      this.jump2list()
    },
    valiData() {
      const v1 = this.handleValid('form')
      return Promise.all([v1])
    },
    saveData(params) {
      this.setBtnLoading('save', true)
      if (params.id) {
        const resourceApiIds = this.$refs.apiTree.getCheckedNodes().filter(item => item.type === '30').map(item => item.id)
        const resourceMenuIds = this.$refs.menuTree.getCheckedKeys()
        console.log(resourceApiIds, resourceMenuIds)
        const resourceIds = resourceApiIds.concat(resourceMenuIds)
        params = { roleId: params.id, resourceIds: resourceIds }
        return bindResource(params).then(res => {
          this.setBtnLoading('bind', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '修改异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '修改成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '修改异常！', message: err.message })
        })
      }
    },
    findById(id) {
      findById({ id: id }).then(res => {
        if (res.data.flag) {
          this.formData = res.data.result
          findByRoleId({ roleId: id }).then(res => {
            if (res.data.flag) {
              if ((res.data.result) != null) {
                this.defaultCheckedKeys = (res.data.result).map(function(temp) {
                  return temp.relResourceId
                })
              }
            } else {
              this.$notify.error({ title: '查询失败!', message: res.data.message })
            }
          })
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    initData() { // 初始化数据
      console.log('初始化数据')
      this.initOptionsData()
      const id = this.id
      if (id) {
        // 初始化修改时的数据
        this.initUpdateData(id)
      }
    },
    initUpdateData(id) {
      this.findById(id)
    },
    initOptionsData() {
      this.loadMenuNode(null, null)
      this.loadApiNode(null, null)
    },
    checkNode(data, checkNode, elem) {
      // console.log(data, checkNode)
      // console.log(this.$refs.menuTree.getCheckedKeys())
    },
    // 加载菜单节点
    loadMenuNode(node, resolve, checkNodes) {
      let parentId = null
      let resourceType = 10
      if (node != null && node.data) {
        parentId = node.data.id
        resourceType = resourceType + 10
      }
      const parems = { 'parentId': parentId, resourceType: resourceType, lazyLoad: false }
      getTree(parems).then(res => {
        if (res.data.flag) {
          const data = res.data.result
          if (resolve) {
            resolve(data)
          } else {
            this.treeMenuData = data
          }
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    // 加载Api节点
    loadApiNode(node, resolve, checkNodes) {
      let appId = null
      let resourceType = 30
      if (node != null && node.data) {
        appId = node.data.id
        resourceType = resourceType + 10
      }
      const parems = { 'appId': appId, resourceType: resourceType }
      getApiTree(parems).then(res => {
        if (res.data.flag) {
          const data = res.data.result
          if (resolve) {
            resolve(data)
          } else {
            this.treeApiData = data
          }
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    }
  }
}

</script>

<style scoped>
.el-divider--horizontal {
  margin: 5px 0;
}
</style>
